/* cl.ext.RadioCheckbox 0.1*/
(
    function (factory) {
        if (typeof define === 'function' && define.amd) {
            define(['jquery'], factory);
        } else if (typeof module === 'object' && module.exports) {
            module.exports = function( root, jQuery ) {
                if ( jQuery === undefined ) {
                    if ( typeof window !== 'undefined' ) {
                        jQuery = require('jquery');
                    }
                    else {
                        jQuery = require('jquery')(root);
                    }
                }
                factory(jQuery);
            };
        } else {
            factory(jQuery);
        }
    }(
    function ($){
        var defaults={
            type:"radio",//radio checkbox
            theme:"default",// default image,
            attrName:"",//name属性
            defaultInfo:{},//width height
            imageInfo:{width:140,height:70,isTitle:true,titlepos:"bottom",describeInfo:{pos:"right",showStyle:"",cls:""}},//describeInfo:cls|width|height|pos|showStyle(vertical|dotdotdot)
            class:"",
            isEvent:true,
            isInline:true,
            data:[],ajax:{},
            initValue:"",
            initIndex:-1,
            afterAjaxCallback:null,
            initCallback:null,
            changeCallback:null
        };
        var $modalCommon={
            getDefaults :function () {
                return defaults
            },
            getOptions : function (elementData,options) {
                options=$.ExtCommon.isCheckEmpty(options)?{}:options;
                var optionBase =$.ExtCommon.initMergeJson(elementData,options);
                optionBase =$.ExtCommon.initMergeJson(this.getDefaults(),optionBase);
                if(!optionBase.isInline && optionBase.defaultInfo){
                    optionBase.defaultInfo.width=null;
                }
                return optionBase
            },
            getStrHtml:function(options){
                var html="";
                if(!$.ExtCommon.isCheckEmpty(options.data)){
                    switch(options.theme){
                        case "default":
                            if(options.type==="radio"){
                                html=this.getHtmlRadio(options);
                            }else  if(options.type==="checkbox"){
                                html=this.getHtmlCheckBox(options);
                            }
                            break;
                        case "image":
                            html=this.getHtmlImage(options);
                            break;
                    }
                }
                /*if(html.length==0){
                    $.ExtNotify.error("无数据");
                }*/
                return html;
            },
            getHtmlCheckBox:function(options){
                var strCheckBox= $.map(options.data,function(info){
                    var strStyle= $.ExtCommon.isCheckEmpty(options.defaultInfo)?""
                        : 'style="' + (options.defaultInfo.width ? ("width:" + (options.defaultInfo.width === "auto" ? "auto" : options.defaultInfo.width + "px")) : "") + '"';
                    var parentCls="";
                    var cbDisabled="";
                    if(options.isInline){parentCls+=" checkbox-inline "}
                    if(!$.ExtCommon.isCheckEmpty(info.disabled) && info.disabled){
                        parentCls+=" checkbox-disabled disabled-forever ";
                        cbDisabled='disabled="disabled"';
                    }
                    return '<div class="checkbox checkbox-default '+parentCls+'" '+ strStyle+'>'+
                        '<input type="checkbox" id="cb_'+options.attrName+'_'+info.id+'" name="'+options.attrName+'" value="'+info.id+'" '+cbDisabled+'>'+
                        '<label for="cb_'+options.attrName+'_'+info.id+'">'+info.name+'</label>'+
                    '</div>';
                }).join("");
                return '<div class="panel-checkbox">'+strCheckBox+'</div>';
            },
            getHtmlRadio:function(options){
                var strStyle= $.ExtCommon.isCheckEmpty(options.defaultInfo)?""
                    : 'style="'+(options.defaultInfo.width?("width:"+options.defaultInfo.width+"px"):"")+'"';
                var strRadio= $.map(options.data,function(info){
                    var parentCls="";
                    var rdDisabled="";
                    if(options.isInline){parentCls+=" radio-inline "}
                    if(!$.ExtCommon.isCheckEmpty(info.disabled) && info.disabled){
                        parentCls+=" radio-disabled disabled-forever ";
                        rdDisabled='disabled="disabled"';
                    }
                    return '<div class="radio radio-default '+parentCls+'"  '+ strStyle+'>'+
                        '<input type="radio" id="rd_'+(options.attrName+info.id)+'" name="'+options.attrName+'" value="'+info.id+'" '+rdDisabled+'>'+
                        '<label for="rd_'+(options.attrName+info.id)+'">'+info.name+'</label>'+
                        '</div>';
                }).join("");
                return '<div class="panel-radio">'+strRadio+'</div>';
            },
            getHtmlImage:function(options){
                var defaults=options.imageInfo;
                var strLi= $.map(options.data,function(info){
                    var imgDisabled=!$.ExtCommon.isCheckEmpty(info.disabled) && info.disabled?" imgselect-disabled disabled-forever ":"";
                    var classLi=$.ExtCommon.isCheckEmpty(options.class)?" ":options.class;
                    var describe="";
                    var imgselectCls="imgselect-btn";
                    if(!$.ExtCommon.isCheckEmpty(info.describeText)){
                        var describeCls="imgselect-describe imgselect-describe-"+defaults.describeInfo.pos;
                        var describeStyle=$.ExtCommon.isCheckEmpty(info.describeColour)?"":"color:"+info.describeColour+";";
                        if(!$.ExtCommon.isCheckEmpty(defaults.describeInfo.width)){describeStyle+=(" width:"+defaults.describeInfo.width+"px; ")}
                        if(defaults.describeInfo.showStyle==="vertical"){describeStyle+=(" height:"+defaults.height+"px;line-height:"+defaults.height+"px;")}
                        else if(defaults.describeInfo.showStyle==="dotdotdot"){describeStyle+=(" height:"+($.ExtCommon.isCheckEmpty(defaults.describeInfo.height)?40:defaults.describeInfo.height)+"px;")}
                        else{if(!$.ExtCommon.isCheckEmpty(defaults.describeInfo.height)){describeStyle+=(" height:"+defaults.describeInfo.height+"; ")}}
                        describe='<div class="'+describeCls+'" style="'+describeStyle+'">'+info.describeText+'</div>';
                        if(defaults.describeInfo.pos==="right"){imgselectCls+=" imgselect-inline-block";classLi+=" imgselect-fs-0"}
                        else if(defaults.describeInfo.pos==="bottom"){imgselectCls+=" imgselect-center"}
                    }
                    var img='<a class="'+imgselectCls+'" href="javascript:" data-init-value="'+info.id+'" style="width:'+defaults.width+'px;height:'+defaults.height+'px;"><img width="'+defaults.width+'" height="'+defaults.height+'" src="'+info.url+'"></a>';
                    var title=defaults.isTitle?'<div class="imgselect-title imgselect-title-'+defaults.titlepos+'">'+info.title+'</div>':"";
                    return '<li name="'+options.attrName+'" class="'+(imgDisabled + classLi)+'">'+(img+title+describe)+'</li>';
                }).join("");
                return '<div class="panel-imgselect"><ul class="imgselect-list">'+strLi+'</ul><div class="clear"></div></div>';
            }
        };
        var modalOperateElement=function(element,options){
            this.elementModal = {elementType:null, parent:null, children:null};
            this.optionModal=options;
            var type=options.type;
            switch(options.theme){
                case "default":
                    if(type==="radio"){
                        this.elementModal.parent=element.find(".panel-radio");
                        this.elementModal.children=element.find(":radio");
                    }else  if(type==="checkbox"){
                        this.elementModal.parent=element.find(".panel-checkbox");
                        this.elementModal.children=element.find(":checkbox");
                    }
                    break;
                case "image":
                    this.elementModal.parent=element.find(".panel-imgselect");
                    this.elementModal.children=element.find("li");
                    break;
            }
            this.elementModal.elementType=options.theme==="default"?options.type:options.theme;
        };
        modalOperateElement.prototype = {
            init:function(){
                var self=this;
                self.bindEvent();
                self.cleanSelectAll();
                if ($.ExtCommon.isCheckEmpty(self.optionModal.initValue)) {
                    var ind = parseInt(self.optionModal.initIndex);
                    if (!$.ExtCommon.isCheckEmpty(self.optionModal.initIndex) && ind > -1) {
                        var initValue=self.optionModal.data[ind].id.toString();
                        self.setSelectValue(initValue,self.optionModal.type,null,true);
                    }
                }else{
                    self.setSelectValue(self.optionModal.initValue,self.optionModal.type,null,true);
                }
                if (self.optionModal.initCallback) {
                    var selectInitValue=$.ExtCommon.isCheckEmpty(self.optionModal.initValue)?"":self.getInitValue(self.optionModal.initValue,self.optionModal.type);
                    var disabledForeverCount=self.getDisabledForever(this.elementContainer);
                    self.hideAnimation();
                    setTimeout(function(){
                        self.optionModal.initCallback(self.optionModal.data,selectInitValue,disabledForeverCount);
                    },200);
                }
            },
            bindEvent:function(){
                switch(this.optionModal.theme){
                    case "default":
                        if(this.optionModal.type==="radio"){
                            this.bindEventRadio();
                        }else  if(this.optionModal.type==="checkbox"){
                            this.bindEventCheckbox();
                        }
                        break;
                    case "image":
                        this.bindEventImage();
                        break;
                }
            },
            bindEventRadio:function(){
                var self=this;
                if(self.optionModal.changeCallback){
                    self.elementModal.children.off("change").on("change", function(){
                        self.triggerRadioChange()
                    });
                }
            },
            triggerRadioChange:function(){
                if(this.optionModal.changeCallback){
                    var values= this.getSelectValue();
                    var count=values.length===0?0:1;
                    var valueList=this.getValueList(values);
                    this.optionModal.changeCallback(values,count,valueList[0])
                }
            },
            bindEventCheckbox:function(){
                var self=this;
                if(self.optionModal.changeCallback){
                    self.elementModal.children.off("change").on("change", function(){
                        var values= self.getSelectValue();
                        var isAll=self.checkIsAll();
                        var count=values.length===0?0:values.split(",").length;
                        var valueList=self.getValueList(values);
                        self.optionModal.changeCallback(values,isAll?-1:count,valueList,self.optionModal.attrName)
                    });
                }
            },
            bindEventImage:function(){
                var self=this;
                self.elementModal.children.filter(":not(.disabled-forever)").off("click").on("click", function(e){
                    var _this=$(this);
                    if(!_this.hasClass("disabled-forever")){
                        var isSelected=_this.hasClass("selected");
                        var isCallback=true;
                        if(self.optionModal.type==="radio"){
                            if(isSelected){
                                isCallback=false;
                            }else{
                                self.settingSelected(self.elementModal.children.filter(":not(.disabled-forever).selected"),false);
                                self.settingSelected(_this,true);
                            }
                        }else if(self.optionModal.type==="checkbox"){
                            self.settingSelected(_this,!isSelected);
                        }
                        if(isCallback && self.optionModal.changeCallback){
                            var values= self.getSelectValue();
                            var isAll=self.checkIsAll();
                            var count=values.length===0?0:values.split(",").length;
                            var valueList=this.getValueList(values);
                            self.optionModal.changeCallback(values,isAll?-1:count,self.optionModal.type==="radio"?valueList[0]:valueList)
                        }
                    }
                    e.stopPropagation();
                });
            },
            getSelectValue:function(){
                var value="";
                switch(this.elementModal.elementType){
                    case "radio":
                        value=this.elementModal.parent.find(":radio:checked").val();
                        break;
                    case "checkbox":
                        var objCheckboxSelect=this.elementModal.parent.find(":checkbox:checked");
                        value= objCheckboxSelect.length===0?"": $.map(objCheckboxSelect,function(item){
                            return $(item).val()
                        }).join(",");
                        break;
                    case "image":
                        var objImgSelect=this.elementModal.parent.find("li.selected");
                        value= objImgSelect.length===0?"": $.map(objImgSelect,function(item){
                            return $(item).find(".imgselect-btn").data("initValue")
                        }).join(",");
                        break;
                }
                return value;
            },
            getValueList:function(values){
                var list=[];
                if(!$.ExtCommon.isCheckEmpty(values)){
                    var arrValue=values.split(",");
                    list= $.map(this.optionModal.data,function(info){if(arrValue.indexOf(info.id.toString())>-1){return info}});
                }
                return list;
            },
            getInitValue:function(data,type){
                var objType=$.type(data).toLowerCase();
                var arr=[];
                if(!$.ExtCommon.isCheckEmpty(data)) {
                    if (objType === "string") {
                        arr=data.split(",");
                    } else if(objType === "array") {
                        arr=$.map(data,function(info){return info.toString()});
                    }else{
                        arr=data.toString();
                    }
                }
                if(type==="radio" && this.elementModal.elementType==="default"){
                    arr=$.type(arr)==="array"?arr[0]:arr;
                }
                return arr
            },
            setSelectValue:function(data,type,isTriggerChange,isFirst){
                var self=this;
                var arr=self.getInitValue(data,type);
                isFirst= $.ExtCommon.isCheckBoolean(isFirst)?isFirst:false;
                isTriggerChange= $.ExtCommon.isCheckEmpty(isTriggerChange)?false:isTriggerChange;
                self.cleanSelectAll();
                if(!$.ExtCommon.isCheckEmpty(arr)){
                    var els=isFirst?self.elementModal.children:self.elementModal.children.filter(":not(.disabled-forever)");
                    $.each(els,function(i,item){
                        var _this=$(item);
                        var value="";
                        switch(self.elementModal.elementType){
                            case "radio":
                                value= _this.val();
                                break;
                            case "checkbox":
                                value=_this.val();
                                break;
                            case "image":
                                value=_this.find(".imgselect-btn").data("initValue");
                                break;
                        }
                        if(arr.indexOf(value.toString())>-1){
                            self.settingSelected(_this,true,isTriggerChange);
                        }
                    })
                }
            },
            settingSelected:function(obj,isChecked,isTriggerChange){
                isTriggerChange= $.ExtCommon.isCheckEmpty(isTriggerChange)?false:isTriggerChange;
                switch(this.elementModal.elementType){
                    case "radio":
                        obj.prop("checked",isChecked);
                        if(isTriggerChange){this.triggerRadioChange()}
                        break;
                    case "checkbox":
                        obj.prop("checked",isChecked);
                        break;
                    case "image":
                        obj.addClass("img-animation");
                        if(isChecked){
                            obj.addClass("selected")
                        }else{
                            obj.removeClass("selected")
                        }
                        break;
                }
            },
            setSelectAll:function(){
                var self=this;
                switch(self.elementModal.elementType){
                    case "radio":
                        $.each(self.elementModal.children,function(i,item){
                            var _this=$(item);
                            if(!_this.parent().hasClass("radio-disabled")){
                                self.settingSelected(_this,true);
                            }
                        });
                        break;
                    case "checkbox":
                        $.each(self.elementModal.children,function(i,item){
                            var _this=$(item);
                            if(!_this.parent().hasClass("checkbox-disabled")){
                                self.settingSelected(_this,true);
                            }
                        });
                        break;
                    case "image":
                        self.settingSelected(self.elementModal.children.filter(":not(.imgselect-disabled)"),true);
                        break;
                }
            },
            cleanSelectAll:function(){
                var self=this;
                switch(self.elementModal.elementType){
                    case "radio":
                        $.each(self.elementModal.children,function(i,item){
                            var _this=$(item);
                            if(!_this.hasClass("radio-disabled")){
                                self.settingSelected(_this,false);
                            }
                        });
                        break;
                    case "checkbox":
                        $.each(self.elementModal.children,function(i,item){
                            var _this=$(item);
                            if(!_this.hasClass("checkbox-disabled")){
                                self.settingSelected(_this,false);
                            }
                        });
                        break;
                    case "image":
                        self.settingSelected(self.elementModal.children.filter(":not(.imgselect-disabled)"),false);
                        break;
                }
            },
            checkIsAll:function(){
                var isAll=false;
                switch(this.elementModal.elementType){
                    case "radio":
                        isAll=false;
                        break;
                    case "checkbox":
                        isAll=this.elementModal.parent.find(":checked").length===this.elementModal.children.filter(":not(.disabled-forever)").length;
                        break;
                    case "image":
                        isAll=this.elementModal.parent.find("li.selected").length===this.elementModal.children.filter(":not(.disabled-forever)").length;
                        break;
                }
                return isAll;
            },
            destroyHtml:function(){
                this.elementModal.parent.off();
                this.elementModal.children.off();
                this.elementModal.parent.empty().remove();
                this.elementModal.elementType=null;
                this.elementModal.parent=null;
                this.elementModal.children=null;
            },
            disabledValue:function(value){
                var self=this;
                if(!$.ExtCommon.isCheckEmpty(value)){
                    var strType=$.type(value).toLowerCase();
                    var arrValue=[];
                    switch(strType){
                        case "array":
                            arrValue=value;
                            break;
                        case "string":
                            arrValue=value.split(",");
                            break;
                    }
                    if(arrValue.length>0){
                        $.each(arrValue,function(i,info){
                            var id=info.toString();
                            switch(self.elementModal.elementType){
                                case "radio":
                                    var _rd=self.elementModal.children.find("rd_"+(self.optionModal.attrName+id));
                                    _rd.prop("disabled",true).parent().addClass("radio-disabled");
                                    _rd.off();
                                    break;
                                case "checkbox":
                                    var _cb=self.elementModal.children.find("cb_"+(self.optionModal.attrName+id));
                                    _cb.prop("disabled",true).parent().addClass("checkbox-disabled");
                                    _cb.off();
                                    break;
                                case "image":
                                    var _a=self.elementModal.children.find("a[data-initValue='"+id+"']");
                                    _a.parent().addClass("imgselect-disabled").off();
                                    break;
                            }
                        });
                    }
                }
            },
            disabledAll:function(){
                this.elementModal.children.off();
                switch(this.elementModal.elementType){
                    case "radio":
                        $.each(this.elementModal.children,function(i,item){
                            var _this=$(item);
                            var _thisParent=_this.parent();
                            if(!_thisParent.hasClass("disabled-forever")){
                                _this.prop("disabled",true);
                                _thisParent.addClass("radio-disabled");
                            }
                        });
                        break;
                    case "checkbox":
                        $.each(this.elementModal.children,function(i,item){
                            var _this=$(item);
                            var _thisParent=_this.parent();
                            if(!_thisParent.hasClass("disabled-forever")){
                                _this.prop("disabled",true);
                                _thisParent.addClass("checkbox-disabled");
                            }
                        });
                        break;
                    case "image":
                        this.elementModal.children.filter(":not(.disabled-forever)").addClass("imgselect-disabled");
                        break;
                }
            },
            cleanDisabledAll:function(){
                this.bindEvent();
                switch(this.elementModal.elementType){
                    case "radio":
                        this.elementModal.children.filter(":not(.disabled-forever)").prop("disabled",false).parent().removeClass("radio-disabled");
                        break;
                    case "checkbox":
                        this.elementModal.children.filter(":not(.disabled-forever)").prop("disabled",false).parent().removeClass("checkbox-disabled");
                        break;
                    case "image":
                        this.elementModal.children.filter(":not(.disabled-forever)").removeClass("imgselect-disabled");
                        break;
                }
            },
            getDisabledForever:function(){
                return this.elementModal.children.filter(".disabled-forever");
            },
            hideAnimation:function(){
                switch(this.elementModal.elementType){
                    case "radio":
                        break;
                    case "checkbox":
                        break;
                    case "image":
                        this.elementModal.children.removeClass("img-animation");
                        break;
                }
            }
        };
        var RadioCheckboxExtModal = function(element, options) {
            var self=this;
            self.element = $(element);
            self.elementContainer={elementType:null, parent:null, children:null};
            self.optionBase=$modalCommon.getOptions(self.element.data(),options);
            if(!$.ExtCommon.isCheckEmpty(self.optionBase.ajax.url)){
                var url=self.optionBase.ajax.url;
                var para=self.optionBase.ajax.data;
                para= $.ExtCommon.isCheckEmpty(para)?{}:para;
                $.ExtAjax.initGet({url:url,data:para,
                    successCallback:function(res){
                        var list=res.success? res.data:[];
                        if(!res.success){ $.ExtNotify.error(res.msg);}
                        self.optionBase.dataOriginalAjax=list;
                        if(self.optionBase.afterAjaxCallback){
                            var templist=self.optionBase.afterAjaxCallback(list);
                            self.optionBase.data= $.ExtCommon.isCheckEmpty(templist)?[]:templist;
                        }else{
                            self.optionBase.data=list;
                        }
                        self.bindHtml();
                    }
                });
            }else{
                self.optionBase.dataOriginalAjax=self.optionBase.data;
                self.bindHtml();
            }
        };
        RadioCheckboxExtModal.prototype = {
            bindHtml:function(){
                var strHtml=$modalCommon.getStrHtml(this.optionBase);
                if(strHtml.length>0){
                    this.element.html(strHtml);
                    this.elementOperate=new modalOperateElement(this.element,this.optionBase);
                    this.elementOperate.init();
                }
            },
            getValue:function(){
                return this.elementOperate.getSelectValue()
            },
            getValueList:function(){
                var strValues=this.getValue();
                var list=[];
                if(!$.ExtCommon.isCheckEmpty(strValues)){
                    var arrValue=this.getValue().split(",");
                    list= $.map(this.optionBase.dataOriginalAjax,function(info){if(arrValue.indexOf(info.id.toString())>-1){return info;}});
                }
                return list;
            },
            getValueInfo:function(){
                var list=this.getValueList();
                return list.length>0?list[0]:{};
            },
            setValue:function(value,isTrigger){
                value= $.ExtCommon.isCheckUndefined(value)?0:value;
                isTrigger= $.ExtCommon.isCheckBoolean(isTrigger)?isTrigger:true;
                if($.type(value).toLowerCase()==="number"){
                    value=value >-1 && value<this.optionBase.dataOriginalAjax.length?value:0;
                    value=this.optionBase.dataOriginalAjax[value].id.toString()
                }
                //isTriggerChange 目前只针对 radio 触发 change事件
                this.elementOperate.setSelectValue(value,this.optionBase.type,isTrigger)
            },
            setAll:function(){
                this.elementOperate.setSelectAll()
            },
            cleanAll:function(){
                this.elementOperate.cleanSelectAll()
            },
            checkIsAll:function(){
                return this.elementOperate.checkIsAll()
            },
            replaceData:function(data){
                this.optionBase.data=data;
                this.optionBase.dataOriginalAjax=data;
                if(this.elementOperate){this.elementOperate.destroyHtml();}
                this.bindHtml();
            },
            disabledValue:function(value){
                this.cleanDisabledAll();
                this.elementOperate.disabledValue(value);
            },
            disabledAll:function(){
                this.elementOperate.disabledAll();
            },
            cleanDisabledAll:function(){
                this.elementOperate.cleanDisabledAll();
            },
            hideAnimation:function(){
                this.elementOperate.hideAnimation();
            }
        };
        $.fn.ExtRadioCheckbox = function(options) {
            var dataFun;
            this.each(function() {
                var el = $(this);
                var tempData=el.data('ExtRadioCheckbox');
                if (tempData) {
                    if (typeof  options === "string") {
                        if (tempData[options]) {
                            dataFun =tempData[options]()
                        } else {
                            dataFun = tempData
                        }
                    } else {
                        dataFun = tempData
                    }
                } else {
                    dataFun = new RadioCheckboxExtModal(el, options);
                    el.data('ExtRadioCheckbox', dataFun);
                }
            });
            return dataFun;
        };
        return RadioCheckboxExtModal;
    })
);
